package top.dreamix.njitkit.data.network

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "network_settings")

class AccountRepository(private val context: Context) {

    private val accountsKey = stringPreferencesKey("accounts_json")
    private val networkSettingKey = stringPreferencesKey("network_setting_json")


    val accountsFlow: Flow<List<Account>> = context.dataStore.data
        .map {
            val jsonString = it[accountsKey]
            if (jsonString.isNullOrEmpty()) {
                emptyList()
            } else {
                Json.decodeFromString<List<Account>>(jsonString)
            }
        }

    val networkSettingFlow: Flow<NetworkSetting> = context.dataStore.data
        .map {
            val jsonString = it[networkSettingKey]
            if (jsonString.isNullOrEmpty()) {
                NetworkSetting()
            } else {
                Json.decodeFromString<NetworkSetting>(jsonString)
            }
        }

    suspend fun saveAccounts(accounts: List<Account>) {
        val jsonString = Json.encodeToString(accounts)
        context.dataStore.edit {
            it[accountsKey] = jsonString
        }
    }

    suspend fun saveNetworkSetting(networkSetting: NetworkSetting) {
        val jsonString = Json.encodeToString(networkSetting)
        context.dataStore.edit {
            it[networkSettingKey] = jsonString
        }
    }
}
